<?php
include 'logic_layer.php';


if (!isset($_SESSION)) {
    session_start();
}

//make sure the session starts from the index page
//and that the session step matched current page
if (!isset($_SESSION["step"]) || $_SESSION["step"] != "rating") {
    header('Location: index.php');
}

if (!isset($_SESSION["recipe_number"])) {
    $_SESSION["recipe_number"] = 1;
}

//get all recipes
$recipes = getRecipes();
?>

<!DOCTYPE html>
<html>
    <head>
        <title>Tutorial</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-Equiv="Cache-Control" Content="no-cache">
        <meta http-Equiv="Pragma" Content="no-cache">
        <meta http-Equiv="Expires" Content="0">
        <!-- Bootstrap -->
        <link href="assets/js/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
        <!-- Main -->
        <link href="main.css" rel="stylesheet" media="screen">
        <!-- Starbox -->
        <link rel="stylesheet" type="text/css" href="assets/js/starbox/css/starbox.css" />

    </head>

    <body>
        <!-- Part 0: Steps -->
        <div class="navbar navbar-fixed-top">
            <div class="navbar-inner">
                <div class="steps">
                    <p class="steps-done">Welcome &#10140; Category &#10140; Outline &#10140; Personality Test &#10140; IFTTT Tutorial &#10140;</p>
                    <p class="step-current">Rating Recipes</p>
                    <p class="steps-pending"> &#10140; Creating a Recipe &#10140; Questionnaire</p>
                </div>
            </div>
        </div>

        <div id="loader" class="loader"></div>
        <table style="width: 100%;">
            <tr>
                <td style="padding-left: 20px;float: left;">
                    <p class="lead" style="text-align:center;">Please rate this recipe based on your interest level (1 star being least desired, 5 stars being most desired)</p>
                </td>
                <td style="padding-right: 20px;float: right;">
                    <pre style="padding: 1px;"><div id="recipieRater"></div></pre>
                </td>
            </tr>
            
        </table>        

        <iframe id="recipe" class="recipe-iframe" frameborder="0"></iframe>

        <div id="bar" class="tutorial-about-bar">
            <table style="width: 100%;">
                <tr>
                    <td style="float:left;text-align:left; width: 200px;">
                        <button style="width: 190px;" id="prevButton" class="btn btn-inverse btn-large" onclick="if (this.className.indexOf('disabled') === -1) {
                                    loadRecipe(OFFSET.PREVIOUS)
                                }
                                ;" type="button" >&larr; Previous Recipe</button>
                    </td>
                    <td style="width: 100%;vertical-align: middle;" valign="middle">
<!--                        <span class="badge badge-info" id="progress-text" style="margin-bottom: 2px;"> </span>-->
                        <div class="progress progress-info" style="height: 44px;">
                            <div id="progress-bar" class="bar" style="width: 0%;"><br><span class="badge badge-inverse" id="progress-text" style="visibility: hidden;font-size: 13px;"> </span></div>
                        </div>
                    </td>
                    <td style="float:right;text-align:right; width: 200px" >
                        <button style="width: 190px;" id="nextButton" class="btn btn-inverse btn-large" onclick="if (this.className.indexOf('disabled') === -1) {
                                    if (this.innerHTML === 'Continue') {
                                        continueStudy();
                                    } else {
                                        loadRecipe(OFFSET.NEXT);
                                    }
                                }" type="button">Next Recipe &rarr;</button>
                    </td>
                </tr>
            </table>
        </div>

        <form action='index.php' method='post' name='frm'>
            <input type='hidden' value='create' name="step" />
        </form>

        <!-- Le javascript
        ================================================== -->
        <script src="assets/js/jquery/jquery-2.0.3.min.js"></script>
        <script src="assets/js/bootstrap/js/bootstrap.min.js"></script>
        <script src="assets/js/bootbox/bootbox.min.js"></script>
        <script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/prototype/1/prototype.js'></script>
        <script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/scriptaculous/1/scriptaculous.js'></script>
        <script type='text/javascript' src='assets/js/starbox/js/starbox.js'></script>

        <script>
                            var OFFSET = {
                                CURRENT: 0,
                                NEXT: 1,
                                PREVIOUS: -1
                            }
                            var recipes = [<?php echo '"' . implode('","', $recipes) . '"'; ?>];

                            var recipeNumber = <?php echo $_SESSION['recipe_number']; ?>;

                            var recipeRate = 0;
                            //==============
                            var loadRecipe = function(offset) {

                                if (recipeNumber + offset >= 1 && recipeNumber + offset <= recipes.length) {
                                    //update recipe number variable
                                    recipeNumber += offset;

                                    //update the iframe
                                    jQuery('#recipe').hide();
                                    document.getElementById("recipe").contentWindow.location.href = recipes[recipeNumber - 1];
                                    jQuery('#loader').show();
                                    disableBar();

                                    jQuery('#recipe').load(function() {
                                        jQuery('#recipe').show();
                                        jQuery('#loader').hide();

                                        loadStarbox();

                                        //update the counter
                                        jQuery('#progress-text').html('(' + recipeNumber + '/' + recipes.length + ')');
                                        //update the progress bar
                                        jQuery('#progress-bar').css("width", parseFloat((100 * recipeNumber) / recipes.length).toFixed(2) + "%");

                                        //update the buttons
                                        if (recipeNumber === 1) {
                                            //disable previous button
                                            jQuery('#prevButton').attr('class', 'btn btn-inverse btn-large disabled');
                                            jQuery('#nextButton').attr('class', 'btn btn-inverse btn-large' + (recipeRate == 0 ? " disabled" : ""));
                                            jQuery('#nextButton').html('Next Recipe &rarr;');
                                        } else if (recipeNumber === recipes.length) {
                                            jQuery('#prevButton').attr('class', 'btn btn-inverse btn-large');
                                            //disable next button and change it to continue
                                            jQuery('#nextButton').attr('class', 'btn btn-success btn-large' + (recipeRate == 0 ? " disabled" : ""));
                                            jQuery('#nextButton').html('Continue');
                                        } else {
                                            //normal
                                            jQuery('#prevButton').attr('class', 'btn btn-inverse btn-large');
                                            jQuery('#nextButton').attr('class', 'btn btn-inverse btn-large' + (recipeRate == 0 ? " disabled" : ""));
                                            jQuery('#nextButton').html('Next Recipe &rarr;');
                                        }
                                    });


                                    //change recipie number in the server as well
                                    new Ajax.Request('logic_layer.php', {
                                        parameters: {function_name: 'setRecipeNumber', recipe_number: recipeNumber}
                                    });
                                }


                            }

                            //==============
                            var disableStarbox = function() {
                                new Starbox('recipieRater', 0, {overlay: 'big.png', stars: 5, buttons: 5, rerate: true, className: 'pointy', total: 0, locked: true});
                                // observing all starboxes
                                document.observe('starbox:rated', saveRate);
                            }

                            //==============
                            var loadStarbox = function() {
                                //get recipe rate form the server
                                var request = new XMLHttpRequest();
                                request.open('POST', 'logic_layer.php', false);  // `false` makes the request synchronous
                                request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                                request.send("function_name=getRecipeRate&recipe_number=" + recipeNumber);
                                recipeRate = parseInt(request.responseText);

                                //create a new starbox instance
                                new Starbox('recipieRater', recipeRate, {overlay: 'big.png', stars: 5, buttons: 5, rerate: true, className: 'pointy', total: 0, locked: false});
                                // observing all starboxes
                                document.observe('starbox:rated', saveRate);
                            }

                            //==============
                            var continueStudy = function() {
                                // go to the next step
                                document.frm.submit();
                            }

                            //==============
                            var disableBar = function() {
                                //disable buttons
                                jQuery('#prevButton').attr('class', 'btn btn-inverse btn-large disabled');
                                jQuery('#nextButton').attr('class', 'btn btn-inverse btn-large disabled');
                                disableStarbox();
                            }

                            //==============
                            var resizeIframe = function() {
                                jQuery('#recipe').css('top', jQuery('.navbar navbar-fixed-top').height() + jQuery('.lead').height() + 45);
                                jQuery('#recipe').height(jQuery(document).height() - parseInt(jQuery('#recipe').css('top')) - jQuery('#bar').height() - 5);
                                jQuery('#recipe').width(jQuery(document).width());
                            }

                            //==============
                            var resizeLoader = function() {
                                var pos = jQuery('#recipe').offset();

                                jQuery("#loader").css({position: "absolute",
                                    height: jQuery('#recipe').height() + 1, width: jQuery('#recipe').width(),
                                    top: pos.top, left: pos.left});
                            }

                            //==============
                            var saveRate = function(event) {

                                new Ajax.Request('logic_layer.php', {
                                    parameters: {function_name: 'saveRecipeRate', recipe_number: recipeNumber, recipe_rate: event.memo.rated},
                                    onSuccess: function(transport) {
                                        jQuery('#nextButton').attr('class', jQuery('#nextButton').attr('class').replace(" disabled", ""))
                                    }
                                });
                            }

                            //load current recipe
                            jQuery(window).resize(function() {
                                resizeIframe();
                                resizeLoader();
                            });

                            jQuery(window).resize();
                            loadRecipe(OFFSET.CURRENT);
                            loadStarbox();
        </script>

    </body>
</html>
